package org.example.day05;

/**
 * 第二章节2.2.8.3:细化验证3个结论
 *      结论3: 当其他线程执行x对象方法里面的synchronized(this)代码块时也呈现同步效果
 */
public class MyThread3 {
    //线程A中用到的锁是m3对象，线程B调用m3.print()方法，该方法中的this锁同样也是m3对象，达到了同步。
    public void print(){
        synchronized(this){
            System.out.println("getLock Time = " + System.currentTimeMillis() + " ThreadName = " + Thread.currentThread().getName());
            System.out.println("----------------------------");
            System.out.println("releaseLock Time = " + System.currentTimeMillis() + " ThreadName = " + Thread.currentThread().getName());
        }
    }
    public static void main(String[] args) throws InterruptedException {
        Service3 service = new Service3();
        MyThread3 m3 = new MyThread3();
        Thread3A ta = new Thread3A(service, m3);
        ta.setName("A");
        ta.start();
        Thread.sleep(100); //确保A线程先拿到锁
        Thread3B tb = new Thread3B(m3);
        tb.setName("B");
        tb.start();
    }
}

class Service3 {
    public void testMethod(MyThread3 m3){
        synchronized (m3){
            try {
                System.out.println("getLock Time = " + System.currentTimeMillis() + " ThreadName = " + Thread.currentThread().getName());
                Thread.sleep(5000);
                System.out.println("releaseLock Time = " + System.currentTimeMillis() + " ThreadName = " + Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Thread3A extends Thread{
    private Service3 sv;
    private MyThread3 m3;

    public Thread3A(Service3 sv, MyThread3 m3) {
        this.sv = sv;
        this.m3 = m3;
    }

    @Override
    public void run() {
        sv.testMethod(m3);
    }
}

class Thread3B extends Thread{
    private MyThread3 m3;

    public Thread3B(MyThread3 m3) {
        this.m3 = m3;
    }

    @Override
    public void run() {
        m3.print();
    }
}